<?php

namespace App\Http\Controllers\Home;

use App\Models\Home\UserInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Models\Home\Weibo;
use App\Http\Controllers\Controller;

class FeedController extends Controller
{
    //feed流
    public function index(Request $request)
    {
        $where = '1';
        if ($request->isMethod('post')) {
            $search = $request->search;
            $where .= ' and content like "%' . $search . '%"';
        }

        //当前用户id
        $user_id = Session::get('user.id');
        //关注的人id
        $follows = UserInfo::where('user_id', $user_id)->first()->following;
        //如果不存在关注的人，则只显示自己的微博记录
        if (!$follows) {
            $feeds = Weibo::join('user_infos', 'user_infos.user_id', '=', 'weibos.user_id')
                ->select('weibos.*', 'user_infos.*')
                ->where('is_show', 1)
                ->where('weibos.user_id', $user_id)
                ->whereRaw($where)
                ->orderBy('created_at', 'desc')
                ->get()
                ->toArray();
        } else {
            //关注的人id转为数组
            $follows = explode(',', $follows);
            //将自己的用户id推入数组
            array_push($follows, $user_id);
            //查出关注的人和自己的所有微博
            $feeds = Weibo::leftJoin('user_infos', 'user_infos.user_id', '=', 'weibos.user_id')
                ->select('weibos.*', 'user_infos.user_id', 'user_infos.nickname', 'user_infos.avatar')
                ->where('is_show', 1)
                ->whereIn('weibos.user_id', $follows)
                ->whereRaw($where)
                ->orderBy('created_at', 'desc')
                ->get();
        }
        $a = UserInfo::select('favorites', 'likes')
            ->where('user_id', '=', $user_id)
            ->first()
            ->toArray();
        foreach ($feeds as $k => $v) {
            if ($v['is_forward']) {
                $forward_weibo = Weibo::join('user_infos', 'user_infos.user_id', '=', 'weibos.user_id')
                    ->select('weibos.*', 'user_infos.user_id', 'user_infos.nickname')
                    ->where('weibos.id', $v['is_forward'])
                    ->first()
                    ->toArray();
                $feeds[$k]['is_forward'] = $forward_weibo;
            }
            $feeds[$k]['favorites'] = $a['favorites'];
            $feeds[$k]['likes'] = $a['likes'];
        }
        return view('home.index', ['feeds' => $feeds]);
    }
}